import { Injectable } from '@nestjs/common';
import axios from 'axios';

@Injectable()
export class GoogleOAuthService {
  private readonly clientId =
    process.env.NODE_ENV !== 'development'
      ? '82716260351-1co5qnvhctqb4jluo5n537a83o9otadt.apps.googleusercontent.com'
      : '82716260351-eunjm8imnr6pc4djgnoaa9mvdoa08nsh.apps.googleusercontent.com';

  private readonly clientSecret = process.env.GOOGLE_CLIENT_SECRET;
  private readonly redirectUri = 'http://localhost:3000/auth/google/callback';

  /**
   * 生成OAuth2授权URL
   */
  generateAuthUrl(): string {
    const params = new URLSearchParams({
      client_id: this.clientId,
      redirect_uri: this.redirectUri,
      scope: 'openid email profile',
      response_type: 'code',
      access_type: 'offline',
      prompt: 'consent',
    });

    return `https://accounts.google.com/o/oauth2/v2/auth?${params.toString()}`;
  }

  /**
   * 使用授权码交换Access Token
   */
  async exchangeCodeForToken(authorizationCode: string) {
    try {
      const response = await axios.post(
        'https://oauth2.googleapis.com/token',
        {
          client_id: this.clientId,
          client_secret: this.clientSecret,
          code: authorizationCode,
          grant_type: 'authorization_code',
          redirect_uri: this.redirectUri,
        },
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        },
      );

      const data = response.data as any;
      return {
        accessToken: data.access_token,
        refreshToken: data.refresh_token,
        expiresIn: data.expires_in,
        tokenType: data.token_type,
      };
    } catch (error) {
      console.error('交换Token失败:', error.response?.data || error.message);
      throw new Error('无法获取Access Token');
    }
  }

  /**
   * 使用Refresh Token获取新的Access Token
   */
  async refreshAccessToken(refreshToken: string) {
    try {
      const response = await axios.post(
        'https://oauth2.googleapis.com/token',
        {
          client_id: this.clientId,
          client_secret: this.clientSecret,
          refresh_token: refreshToken,
          grant_type: 'refresh_token',
        },
        {
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
        },
      );

      const data = response.data as any;
      return {
        accessToken: data.access_token,
        expiresIn: data.expires_in,
        tokenType: data.token_type,
      };
    } catch (error) {
      console.error('刷新Token失败:', error.response?.data || error.message);
      throw new Error('无法刷新Access Token');
    }
  }

  /**
   * 获取用户信息
   */
  async getUserInfo(accessToken: string) {
    try {
      const response = await axios.get(
        'https://www.googleapis.com/oauth2/v2/userinfo',
        {
          headers: {
            Authorization: `Bearer ${accessToken}`,
          },
        },
      );

      const userData = response.data as any;
      return {
        id: userData.id,
        email: userData.email,
        name: userData.name,
        picture: userData.picture,
        verifiedEmail: userData.verified_email,
        locale: userData.locale,
      };
    } catch (error) {
      console.error('获取用户信息失败:', error.response?.data || error.message);
      throw new Error('无法获取用户信息');
    }
  }
}
